from Accounting.Fee.FeeBase import Fee
from Accounting.Entity.Utils import *
from DataAccess.DBConnFactory import DBConnFactory
from string import Template



class FloatingFee(Fee):
	def __init__(self, ref_date, entity, subtype, is_payment_date, is_redem, curncy):
		cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()

		sql_tpl = Template('''select perf_ratio,curncy from fee_conf 
							where entity='${ENTITY}'
							and subtype='${TP}' ''')	
		cursor.execute(sql_tpl.substitute(ENTITY=entity.get_entity_id(), 
										TP=subtype))
		r = cursor.fetchall()
		if not r:
			raise RuntimeError(), ("Fee Config Error")

		self.perf_ratio = r[0][0]
		self.fee_subtype = subtype
		
		Fee.__init__(self, ref_date, r[0][1], is_payment_date, is_redem, entity)
		
	def calculate(self):
		cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
		
		pre_peak = watermark(self.ref_date, self.entity ,self.fee_subtype)
		crt_GAV_per_share = GAV_per_share(self.ref_date, self.entity)	
		
		#Sum Shares Of Children
		sql_tpl = Template('''select sum(shares) from share_account 
							where parent='${ENTITY}'
								and ref_date=TO_DATE('${DATE}','yyyy-mm-dd') 
								and shares<>0''')
		cursor.execute(sql_tpl.substitute(ENTITY = self.entity.get_entity_id(),
											DATE = self.ref_date.isoformat()))					
		r = cursor.fetchall()
		if not r:
			raise RuntimeError(), ("Shares Account Error")	
		shares = r[0][0]			
	
		self.amt = max(crt_GAV_per_share-pre_peak[1], 0)*shares*self.perf_ratio

	def type(self):
		return self.fee_subtype
		
	def category(self):
		return 'PreNAVFee'
	